package com.fjl.controller;

import com.fjl.bean.User;
import com.fjl.bean.UserImgBean;
import com.fjl.service.UserService;
import com.fjl.utils.FileUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * TOOD
 *
 * @author luo
 * @version 1.0
 * @date 2020/5/19 10:22
 */
@Controller(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 查询所有用户，返回 带有用户数据的页面视图
     * @return
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> users = userService.findAll();
        modelAndView.addObject("users",users);
        modelAndView.setViewName("users");
        return modelAndView;
    }
    @RequestMapping("/toLogin")
    public String toIndex(){
        return "login";
    }

    @RequestMapping("/users")
    public String index(Model model,@RequestParam(defaultValue = "1") Integer pageNum,@RequestParam(defaultValue = "3") Integer pageSize){
        PageInfo<User> userPageInfo = userService.selectUser4Page(pageNum, pageSize);

//        将model传传输会前端
        model.addAttribute("pageInfo",userPageInfo);
        model.addAttribute("users",userPageInfo.getList());

        return "users";
    }



    @PostMapping("/addUser")
    @ResponseBody
    public Map<String, Object> addUser(User user, HttpServletRequest request){
        HashMap<String, Object> map = new HashMap<>();
        boolean flag = userService.insertUser(user);
        UserImgBean userImgBean = new UserImgBean();
//        MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
//        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        request = (MultipartHttpServletRequest)request;
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        for (MultipartFile file : files) {
            if(file.isEmpty())
                continue;
            byte[] bytes = new byte[0];

            try {
                bytes = file.getBytes();
                String originalFilename = file.getOriginalFilename();
                originalFilename = originalFilename.substring(originalFilename.lastIndexOf("."));
                String fileName = UUID.randomUUID() + originalFilename;
                boolean bRet = FileUtils.uploadFile(bytes, "static/upload/" + fileName);
                if(!bRet)
                    continue;
                userImgBean.setId(0);
                userImgBean.setUser_id(user.getId());
                userImgBean.setImg("upload/"+fileName);
                int iFlag = userService.insertUserImg(userImgBean);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        if(flag){
            map.put("msg","完成添加");
            return map;
        }else{
            map.put("msg","添加失败");
            return map;
        }
    }
    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/login")
    public String login(@RequestParam(name = "username") String username, @RequestParam("password") String password, HttpSession httpSession){
        User login = userService.login(username, password);
        if(login != null){
            httpSession.setAttribute("user",login);
            return "success";
        }
        else{
            return "error";
        }
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "index";
    }

    @RequestMapping("/deleteUser+{id}+{page}+{pageSize}")
    public String deleteUser(@PathVariable("id") String id, ModelMap modelMap,@PathVariable("page") Integer page,@PathVariable("pageSize") Integer pageSize){
        boolean flag = userService.deleteUser(id);
        PageInfo<User> pageInfo = userService.selectUser4Page(page,pageSize);
        modelMap.addAttribute("users",pageInfo.getList());
        modelMap.addAttribute("pageInfo",pageInfo);
        if(flag)
            return "users";
        return "error";
    }

    /**
     * 查找指定 用户
     * @param id
     * @param modelMap
     * @return
     */
    @RequestMapping("/selectOne")
    public String selectOne(String id,ModelMap modelMap){
        User user = userService.selectOne(id);

        List<UserImgBean> userImgBeans = userService.selectUserImgBeanByUid(user.getId());
        if(user != null && userImgBeans != null){
            modelMap.addAttribute("user",user);
            modelMap.addAttribute("userImgBeans",userImgBeans);
            return "userInfo";
        }
        return "error";
    }

    @RequestMapping("/user+{id}")
    public String findUserModify(@PathVariable("id") String id,ModelMap modelMap){
        User user = userService.selectOne(id);
        modelMap.addAttribute("user",user);
        return "modify";
    }

    @RequestMapping("modify")
    public String modify(User user,ModelMap modelMap){
        boolean flag = userService.updateUser(user);
        if(flag){
            PageInfo<User> pageInfo = userService.selectUser4Page(1,3);

            modelMap.addAttribute("users",pageInfo.getList());
            modelMap.addAttribute("pageInfo",pageInfo);
            return "users";
        }else{
            return "error";
        }
    }

    @RequestMapping("deleteImgById")
    public String deleteImgById(@RequestParam(value = "id") Integer id,@RequestParam(value = "userid") Integer userid,ModelMap map){
        userService.deleteImgByid(id);
        User user = userService.selectOne(String.valueOf(userid));
        List<UserImgBean> userImgBeans = userService.selectUserImgBeanByUid(userid);
        map.addAttribute("user",user);
        map.addAttribute("userImgBeans",userImgBeans);
        return "userInfo";
    }
}
